const { sh } = require("tasksfile");
const chalk = require("chalk");
const path = require('path');
const fs = require('fs');
const config = require("../vue.config.js");
const rawArgv = process.argv.slice(2);
const args = rawArgv.join(" ");

if (process.env.npm_config_preview || rawArgv.includes("--preview")) {
  const report = rawArgv.includes("--report");

  sh(`vue-cli-service build ${args}`);

  const port = config.devServer.port + 1;
  const publicPath = config.publicPath;

  const express = require("express");
  const app = express();
  app.use(express.static(path.resolve(__dirname, "../dist")));
  app.get('*', function(req, res) {
    const html = fs.readFileSync(path.resolve(__dirname, '../dist/index.html'), 'utf-8');
    res.send(html)
  });
  app.listen(port, function() {
    console.log(chalk.green(`> Preview at  http://localhost:${port}${publicPath}`));
    if (report) {
      console.log(chalk.green(`> Report at  http://localhost:${port}${publicPath}report.html`));
    }

  });
} else {
  sh(`vue-cli-service build ${args}`);
}
